package com.hp.authweb.service.sercrity;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.hp.authweb.bean.Result;

@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		String errorMsg = "";
		if(exception instanceof InternalAuthenticationServiceException){
			errorMsg = "用户不存在!";
		}else if(exception instanceof BadCredentialsException){
			errorMsg = "密码错误!";
		}else if(exception instanceof AccountExpiredException){
			errorMsg = "用户已过期!";
		}else if(exception instanceof LockedException){
			errorMsg = "用户已锁定!";
		}
		response.getWriter().write(JSONObject.toJSONString(Result.fail(errorMsg)));
	}
}
